<template>
  <div>
    <a-radio-group :options="curCategory" :default-value="defaultChecked" @change="categoryTypeChange"></a-radio-group>
    <div v-if="value !== 'all'" class="panel body">
      <div v-if="value === 'biz'">
        <!-- 当有两个条件组时显示此项选择 -->
        <a-radio-group v-if="bizpanels.length === 2" :options="bizFilter" v-model="operator_exp" @change="bizChange" />
        <a-tabs
          :activeKey="tabActive"
          type="editable-card"
          :hideAdd="true"
          tab-position="left"
          @edit="removeBizGroupPanel"
          @change="tabChange"
          style="margin-top: 10px"
        >
          <a-tab-pane
            class="tab-pane"
            v-for="(pane, index) in bizpanels"
            :key="pane.key"
            :tab="pane.name"
            :closable="pane.closable"
          >
            <template v-for="(item, idx) in params[index].attrvalues">
              <a-row
                v-if="idx !== 0"
                :key="'bizgroup_1' + idx"
                align="middle"
                type="flex"
                justify="space-between"
                style="margin-top: 10px"
              >
                <a-col :span="24"
                  ><a-switch
                    size="small"
                    style="margin-bottom: 5px"
                    v-model="item.operator"
                    checked-children="且"
                    un-checked-children="或"
                /></a-col>
              </a-row>
              <a-row
                :key="index === 0 ? 'bizgroup_1' + idx + 1 : 'bizgroup_2' + idx + 1"
                align="middle"
                type="flex"
                justify="space-between"
              >
                <a-col :span="5">
                  <a-select v-model="item.keyid">
                    <a-select-option v-for="industry in industrys" :key="industry.keyid" :value="industry.keyid">
                      {{ industry.keyname }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="3">
                  <a-select v-model="item.fuzzy" @change="operatorChange($event, item)">
                    <a-tooltip slot="suffixIcon" placement="top">
                      <template slot="title">
                        <span>模糊支持模糊查询<br />包含支持多值查询</span>
                      </template>
                      <a-icon type="question-circle" :style="{ color: tipColor }" />
                    </a-tooltip>
                    <a-select-option v-for="(op, opidx) in operators" :value="op.value" :key="opidx">
                      {{ op.label }}
                    </a-select-option>
                  </a-select>
                </a-col>
                <a-col :span="8">
                  <a-input v-if="item.fuzzy" placeholder="请输入" v-model="item.keyvalue" allow-clear />
                  <a-select
                    v-else
                    mode="tags"
                    placeholder="请回车输入"
                    v-model="item.keyvalues"
                    allow-clear
                  >
                  </a-select>
                </a-col>
                <a-col :span="2">
                  <a-icon type="plus-circle" @click="addCondition(index)" />
                  <a-icon
                    v-if="idx !== 0"
                    type="minus-circle"
                    style="margin-left: 5px"
                    @click="removeCondition(index, idx)"
                  />
                </a-col>
              </a-row>
            </template>
          </a-tab-pane>
          <!-- 只有一组条件时显示添加组按钮 -->
          <a-button
            v-if="bizpanels.length === 1"
            icon="plus"
            size="small"
            slot="tabBarExtraContent"
            @click="addGroupPanel"
          ></a-button>
        </a-tabs>
      </div>
      <div v-if="value === 'tag'">
        <div>
          <a-radio-group :options="tagFilter" v-model="operator_tag" @change="tagOperatorChange" />
        </div>
        <div>
          <a-select
            mode="multiple"
            style="margin-top: 10px"
            placeholder="请选择标签"
            v-model="params"
            showArrow
            :allowClear="true"
          >
            <a-select-opt-group :label="group.group_name" v-for="group in grouptags" :key="group.group_id">
              <a-select-option v-for="opt in group.tag" :value="opt.id" :key="opt.id">{{ opt.name }}</a-select-option>
            </a-select-opt-group>
          </a-select>
        </div>
      </div>
      <div v-if="value === 'group'">
        <a-button @click="chooseGroup">请选择群<a-icon type="file-search" /></a-button
        ><span style="margin-left: 10px"
          >已选择&nbsp;<span style="color: #40a9ff">{{ group_count }}</span
          >&nbsp;个群</span
        >
        <a-modal
          v-model="groupVisiable"
          title="选择群"
          centered
          :bodyStyle="{ height: '500px' }"
          width="700px"
          @ok="confirmGroups"
          dialog-content
          ant-modal-content
          :maskClosable="false"
        >
          <!-- 自定义div选择部门 -->
          <div class="ant-modal-body">
            <!-- <a-row>
              <a-col :span="12">
                <div class="add-member-left member-div" style="margin-top: -30px">
                  <div class="members">
                    <div style="margin: 10px 0px"></div>
                    <div style="margin-left: -18px">
                      <a-tabs default-active-key="1">
                        <a-tab-pane key="1" tab="组织架构">
                          <a-input-search style="margin-bottom: 8px" placeholder="搜索部门" @change="searchDepart" />
                          <a-tree
                            v-model="checkedKeys"
                            checkable
                            checkStrictly
                            :replaceFields="{ children: 'children', key: 'id', title: 'name' }"
                            :expanded-keys="expandedKeys"
                            :auto-expand-parent="autoExpandParent"
                            :selected-keys="selectedKeys"
                            :tree-data="treeDepart"
                            @expand="onExpand"
                            @select="onSelect"
                            @check="onCheck"
                            class="all-member-list"
                          >
                            <span slot="title" slot-scope="{ name, scopedSlots }" style="color: #08c">
                              <span v-if="scopedSlots.avatar">
                                <a-avatar
                                  style="float: left; margin-top: 2px"
                                  shape="square"
                                  :size="26"
                                  :src="scopedSlots.avatar"
                                />
                                <span v-if="name.substring(6).indexOf(searchValue) > -1">
                                  <span style="margin-left: 5px; line-height: 26px">
                                    {{ name.substring(6).substr(0, name.substring(6).indexOf(searchValue)) }}
                                    <span style="color: #f50">{{ searchValue }}</span>
                                    {{
                                      name
                                        .substring(6)
                                        .substr(name.substring(6).indexOf(searchValue) + searchValue.length)
                                    }}
                                  </span>
                                </span>
                                <span v-else>
                                  <span style="margin-left: 5px; line-height: 26px">{{ name.substring(6) }}</span>
                                </span>
                              </span>
                              <span v-else>
                                <a-icon type="team" />
                                <span v-if="name.indexOf(searchValue) > -1">
                                  <span style="margin-left: 5px; line-height: 26px">
                                    {{ name.substr(0, name.indexOf(searchValue)) }}
                                    <span style="color: #f50">{{ searchValue }}</span>
                                    {{ name.substr(name.indexOf(searchValue) + searchValue.length) }}
                                  </span>
                                </span>
                                <span v-else>
                                  <span style="margin-left: 5px; line-height: 26px">{{ name }}</span>
                                </span>
                              </span>
                            </span>
                          </a-tree>
                        </a-tab-pane>
                      </a-tabs>
                    </div>
                  </div>
                </div>
              </a-col>
              <a-col :span="12" style="padding-left: 30px">
                <p style="color: #787878; max-width: 220px">已选择&nbsp;{{ checkedGroups.length }}&nbsp;个群</p>
                <ul style="width: 100%" class="all-member-right-list">
                  <li style="padding: 8px 0px; width: 90%; clear: both" v-for="item in checkedGroups" :key="item.id">
                    <div class="avatar-and-name" style="float: left">
                      <span class="ant-farimg">{{ item.name }}</span>
                    </div>
                    <a-icon
                      type="close"
                      @click="delGroup(item)"
                      style="float: right; vertical-align: -1.125em; display: block; margin-top: 7px; cursor: pointer"
                    />
                  </li>
                </ul>
              </a-col>
            </a-row> -->
            <a-row>
              <a-form layout="inline">
                <a-row type="flex" justify="space-between">
                  <a-col :span="12">
                    <a-form-item label="群名称">
                      <a-input v-model="input" placeholder="请输入群名称" />
                    </a-form-item>
                  </a-col>
                  <a-col :span="5">
                    <a-button type="primary" @click="searchGroup" icon="search">查询</a-button>
                  </a-col>
                </a-row>
              </a-form>
              <div class="spin-content">
                <b>共{{ groups.length }}个群</b>&nbsp; 已选择&nbsp;
                <a v-text="selectedGroupIds.length"></a>
              </div>
              <a-table
                :columns="group_columns"
                :data-source="groups"
                :pagination="upagination"
                rowKey="chat_id"
                :row-selection="{ selectedRowKeys: selectedGroupIds, onChange: onGroupSelectChange }"
                :scroll="{ y: 270 }"
                @change="tableChange"
              >
                <template slot="owner" slot-scope="text, record">
                  {{ record.owner.name }}
                </template>
              </a-table>
            </a-row>
          </div>
        </a-modal>
      </div>
    </div>
    <a-row v-if="value !== 'group'">
      <a-col>
        <div class="viewmembers">
          <a-icon type="file-search" />查看该消息预计送达人数：<a v-if="!show_people" @click="findCustCount">查看</a>
          <a v-else @click="queryCustList">{{ pepole_count }}</a>
        </div>
      </a-col>
    </a-row>
    <a-modal v-model="visible" title="客户名单" width="70%" :footer="null" :maskClosable="false">
      <p-csm :data="custlist" :type="value" />
    </a-modal>
  </div>
</template>
<script>
import {
  queryTagList,
  queryIndustrys,
  findCustCountByTags,
  queryCustListByTags,
  findCustCountByExp,
  queryCustListByExp,
} from '@/components/Power/BizComponents/CustomerScreening/CustomerScreen'
import { queryCustomerGroupList } from '@/api/customer/customerGroup'
import { APP_USER, TOGGLE_COLOR } from '@/store/mutation-types'
import storage from 'store'
import csm from '@/components/Power/BizComponents/CustomerScreening/CustomerScreenDetail'
const dataList = []
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const key = node.parentid
    dataList.push({
      key,
      title: node.name,
    })
    if (node.children) {
      generateList(node.children)
    }
  }
}

const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some((item) => item.parentid === key)) {
        parentKey = key
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}

export default {
  props: {
    categorys: {
      // 可选条件组
      type: Array,
      default: function () {
        return new Array()
      },
    },
    defaultChecked: {
      // 默认选中条件组
      type: String,
      default: 'all',
    },
    scope: {
      // 客户范围{ ids: ['客服id/部门id'], type: 'user/org'}
      type: Object,
      default: null,
    },
    default: {
      type: Object,
      default: null,
    },
    wxlink: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      useid: '',
      searchValue: '',
      enum_categorys: [
        { label: '全部客户', value: 'all' },
        { label: '业务筛选客户', value: 'biz' },
        { label: '标签筛选客户', value: 'tag' },
        { label: '客户群筛选客户', value: 'group' },
      ],
      value: this.defaultChecked,
      curCategory: [],
      grouptags: [],
      tagFilter: [
        { label: '以下标签满足其中之一', value: 0 },
        { label: '以下标签同时满足', value: 1 },
      ],
      operator_tag: 0, // 标签条件操作符
      bizFilter: [
        { label: '以下业务属性满足其中一组', value: 0 },
        { label: '以下业务属性同时满足', value: 1 },
      ],
      operator_exp: 0, // 业务属性组条件操作符
      industrys: [], // 行业属性
      bizpanels: [
        // 行业条件组控制
        { key: 0, name: '组1', closable: false },
      ],
      operators: [
        { label: '模糊', value: 1 },
        { label: '包含', value: 0 },
      ],
      groupVisiable: false, // 控制显示选群窗口显示
      expandedKeys: [], // 已展开的节点
      autoExpandParent: true, // 自动展开父级
      treeDepart: [], // 树形部门数据
      checkedGroups: [], // 当前中间已选群
      selectedKeys: [],
      checkedKeys: [], // 已选中的部门
      checkedDepart: new Map(), // 已选中的部门及群信息
      group_count: 0, // 已选择群数量
      pepole_count: 0, // 预计发送总人数
      show_people: false, // 控制是否显示发送人数
      visible: false, // 是否显示客户名单
      custlist: [], // 客户名单列表
      tabActive: 0, // 业务属性组
      params: [
        // 客户查询条件
      ],
      user: 'user',
      org: 'org',
      group_columns: [
        {
          title: '群名称',
          dataIndex: 'name',
          key: 'name',
          sorter: (a, b) => a.name.localeCompare(b.name),
          ellipsis: true,
        },
        {
          title: '群主',
          dataIndex: 'owner',
          key: 'owner',
          scopedSlots: { customRender: 'owner' },
          sorter: (a, b) => a.owner.name.localeCompare(b.owner.name),
          ellipsis: true,
        },
        {
          title: '群人数',
          width: '100px',
          dataIndex: 'member_count',
          key: 'member_count',
          sorter: (a, b) => a.member_count - b.member_count,
        },
        {
          title: '群创建时间',
          width: '180px',
          key: 'createtime',
          dataIndex: 'createtime',
          sorter: (a, b) => a.createtime.localeCompare(b.createtime),
        },
      ],
      groups: [],
      upagination: {
        // 表格分页参数
        defaultPageSize: 20,
        total: 0,
        current: 1,
        pageSize: 20,
        showTotal: (total) => `共${total}条数据`,
        showSizeChanger: true,
        pageSizeOptions: ['10', '20', '50'],
      },
      selectedGroupIds: [], // 已选中的群id
      input: ''
    }
  },
  watch: {
    // 通过监听查询参数的变化自动切换预计发送人数的显示
    params: {
      handler(val, oval) {
        this.show_people = false
        let param = {}
        param.type = this.value
        if (this.value === 'biz') {
          param.params = this.paramConvert(this.params)
          param.operator = this.operator_exp
        } else {
          param.params = this.params
          param.operator = this.operator_tag
        }
        if (this.scope !== null) {
          param.scope = this.scope
        }
        if (this.value !== 'group') {
          param.wxlink = this.wxlink
        }
        this.$emit('callback', param)
      },
      immediate: true,
      deep: true,
    },
    operator_tag: {
      handler(val, oval) {
        this.show_people = false
        let param = {}
        param.type = this.value
        if (this.value === 'biz') {
          param.params = this.paramConvert(this.params)
          param.operator = this.operator_exp
        } else {
          param.params = this.params
          param.operator = this.operator_tag
        }
        if (this.scope !== null) {
          param.scope = this.scope
        }
        param.wxlink = this.wxlink
        this.$emit('callback', param)
      },
      immediate: true,
    },
    operator_exp: {
      handler(val, oval) {
        this.show_people = false
        let param = {}
        param.type = this.value
        if (this.value === 'biz') {
          param.params = this.paramConvert(this.params)
          param.operator = this.operator_exp
        } else {
          param.params = this.params
          param.operator = this.operator_tag
        }
        if (this.scope !== null) {
          param.scope = this.scope
        }
        param.wxlink = this.wxlink
        this.$emit('callback', param)
      },
      immediate: true,
    },
    scope: {
      handler(val, oval) {
        this.show_people = false
        let param = {}
        param.type = this.value
        if (this.value === 'biz') {
          param.params = this.paramConvert(this.params)
          param.operator = this.operator_exp
        } else if (this.value === 'group') {
          if (this.scope.type === 'org') {
            this.queryGroupList({ pageno: this.upagination.current - 1, owner_deptid: this.scope.ids[0] })
          } else if (this.scope.type === 'user') {
            this.queryGroupList({ pageno: this.upagination.current - 1, owner_userid: this.scope.ids[0] })
          }
        } else {
          param.params = this.params
          param.operator = this.operator_tag
        }
        if (this.scope !== null) {
          param.scope = this.scope
        }
        if (this.value !== 'group') {
          param.wxlink = this.wxlink
        }
        this.$emit('callback', param)
      },
      immediate: true,
      deep: true,
    },
    value: {
      handler(val, oval) {
        if (val === 'group') {
          if (this.scope.type === 'org') {
            this.queryGroupList({ pageno: this.upagination.current - 1, owner_deptid: this.scope.ids[0] })
          } else if (this.scope.type === 'user') {
            this.queryGroupList({ pageno: this.upagination.current - 1, owner_userid: this.scope.ids[0] })
          }
        }
      },
    },
  },
  computed: {
    tipColor() {
      return this.$store.getters.color // 获取系统主题颜色
    },
  },
  created() {
    // 查询标签组列表
    queryTagList().then((res) => {
      if (res.code === 0) {
        this.grouptags = res.data
      }
    })
    // 查询行业属性
    queryIndustrys({ apptype: 1 }).then((res) => {
      if (res.code === 0) {
        this.industrys = res.data.business
      }
    })

    if (this.categorys.length > 0) {
      this.enum_categorys.forEach((item) => {
        this.categorys.forEach((ite) => {
          if (item.value === ite) {
            this.curCategory.push(item)
          }
        })
      })
    } else {
      this.curCategory = this.enum_categorys
    }

    if (this.default !== null && this.default.type) {
      this.params = this.default.type === 'biz' ? this.paramReVert(this.default.params) : this.default.params
      if (this.default.type === 'tag') {
        this.operator_tag = this.default.operator
      } else if (this.default.type === 'biz') {
        this.operator_exp = this.default.operator
        // 当有两组条件时开启第二个条件组Tab
        if (this.params.length > 1) {
          this.bizpanels.push({ key: 1, name: '组2', closable: true })
        }
      } else if (this.default.type === 'group') {
        this.group_count = this.default.params.length
        this.default.params.forEach((item) => {
          this.selectedGroupIds.push(item.id)
        })

        if (this.default.scope.type) {
          if (this.default.scope.type === 'org') {
            this.queryGroupList({ pageno: this.upagination.current - 1, owner_deptid: this.scope.ids[0] })
          } else if (this.default.scope.type === 'user') {
            this.queryGroupList({ pageno: this.upagination.current - 1, owner_userid: this.scope.ids[0] })
          }
        } else {
          this.queryGroupList({ pageno: this.upagination.current - 1 })
        }
      }
    } else {
      if (this.defaultChecked) {
        if (this.defaultChecked === 'group') {
          this.selectedGroupIds = []
          if (this.scope.type) {
            if (this.scope.type === 'org') {
              this.queryGroupList({ pageno: this.upagination.current - 1, owner_deptid: this.scope.ids[0] })
            } else if (this.scope.type === 'user') {
              this.queryGroupList({ pageno: this.upagination.current - 1, owner_userid: this.scope.ids[0] })
            }
          } else {
            this.queryGroupList({ pageno: this.upagination.current - 1 })
          }
        }
      }
    }
  },
  methods: {
    categoryTypeChange(evt) {
      this.value = evt.target.value
      this.params = []
      if (this.value === 'biz') {
        this.tabActive = 0
        if (this.bizpanels.length > 1) {
          this.bizpanels.splice(1, 1)
        }
        this.params.push({
          order: 0,
          operator: '',
          attrvalues: [{ keyid: '', keyvalue: '', keyvalues: [], operator: false, fuzzy: 1, order: 0 }],
        })
      }
      this.show_people = false
      this.group_count = 0
    },
    tagOperatorChange(value) {
      this.show_people = false
    },
    addGroupPanel() {
      // 添加业务属性条件组函数
      this.bizpanels.push({ key: 1, name: '组2', closable: true })
      // 默认选中新建的tab
      this.tabActive = 1

      // 默认生成一个条件
      this.params.push({
        order: 1,
        operator: '',
        attrvalues: [{ keyid: '', keyvalue: '', keyvalues: [], operator: false, fuzzy: 1, order: 0 }],
      })
    },
    tabChange(active) {
      // 选项卡切换事件
      this.tabActive = active
    },
    removeBizGroupPanel(index) {
      // 删除业务属性条件组函数
      this.bizpanels.splice(index, 1)
      this.params.splice(index, 1)
      this.tabActive = 0
    },
    addCondition(index) {
      // 条件组添加条件函数
      this.params[index].attrvalues.push({
        keyid: '',
        keyvalue: '',
        keyvalues: [],
        operator: false,
        fuzzy: 1,
        order: 0,
      })
    },
    removeCondition(index, idx) {
      // 条件组删除条件函数
      this.params[index].attrvalues.splice(idx, 1)
    },
    operatorChange(val, item) {
      // 操作符改变事件函数
      if (val === 0) {
        item.keyvalue = ''
      } else if (val === 1) {
        item.keyvalues = []
      }
    },
    bizChange(e) {
      this.show_people = false
    },
    findCustCount() {
      // 统计预计发送人数
      if (this.value === 'all' || this.value === 'tag') {
        // 全部客户/按照标签筛选客户

        let params = { operator: this.operator_tag, wxlink: this.wxlink ? 1:0 }
        if (this.scope !== null) {
          if (this.scope.type === this.org) {
            params.follow_deptid = this.scope.ids[0]
          } else if (this.scope.type === this.user) {
            params.follow_userid = this.scope.ids[0]
          }
        }

        // 按照标签统计客户人数
        findCustCountByTags(params, { tags: this.params }).then((res) => {
          if (res.code === 0) {
            this.pepole_count = res.data
            this.show_people = true
          }
        })
      } else if (this.value === 'biz') {
        let params = { apptype: 1, wxlink: this.wxlink ? 1:0 }
        if (this.scope !== null) {
          if (this.scope.type === this.org) {
            params.follow_deptid = this.scope.ids[0]
          } else if (this.scope.type === this.user) {
            params.follow_userid = this.scope.ids[0]
          }
        }
        let valid = true
        this.params.forEach((item) => {
          item.attrvalues.forEach((attr) => {
            if (attr.keyid === '') {
              valid = false
              return false
            }
          })
        })

        if (!valid) {
          this.$message.error('请选择业务属性')
          return
        }

        let body = JSON.parse(JSON.stringify(this.params))
        body = body.map((item) => {
          item.operator = this.operator_exp
          item.attrvalues.forEach((vitem, index) => {
            vitem.order = index
            vitem.operator = vitem.operator ? 1 : 0
            if (vitem.fuzzy === 0 && vitem.keyvalues.length > 0) {
              vitem.keyvalue = vitem.keyvalues.join(',')
            }
            vitem.fuzzy = vitem.fuzzy === 1 ? true : false
            delete vitem.keyvalues
          })
          return item
        })
        // 根据业务属性统计客户人数
        findCustCountByExp(params, body).then((res) => {
          if (res.code === 0) {
            this.pepole_count = res.data
            this.show_people = true
          }
        })
      }
    },
    queryCustList() {
      // 查询客户名单
      this.visible = true
      if (this.value === 'all' || this.value === 'tag') {
        // 全部客户/按照标签筛选客户
        this.custlist = []
        let params = { operator: this.operator_tag, wxlink: this.wxlink ? 1:0 }
        if (this.scope !== null) {
          if (this.scope.type === this.org) {
            params.follow_deptid = this.scope.ids[0]
          } else if (this.scope.type === this.user) {
            params.follow_userid = this.scope.ids[0]
          }
        }
        // 按照标签查询客户人数
        queryCustListByTags(params, { tags: this.params }).then((res) => {
          if (res.code === 0) {
            let conditionkey = new Map()
            // 赋予查询条件标签id
            this.params.forEach((item) => {
              conditionkey.set(item, item)
            })
            let list = []
            if (res.data && res.data.length > 0) {
              list = res.data.map((item) => {
                if (item.corp_tags && item.corp_tags > 0) {
                  item.corp_tags.forEach((vi, index) => {
                    if (!conditionkey.has(vi.tagid)) {
                      delete item.corp_tags[index]
                    }
                  })
                }
                return item
              })
              this.custlist = list
            }
          }
        })
      } else if (this.value === 'biz') {
        this.custlist = []
        let conditionkey = new Map()

        let params = { apptype: 1, wxlink: this.wxlink ? 1:0 }
        if (this.scope !== null) {
          if (this.scope.type === this.org) {
            params.follow_deptid = this.scope.ids[0]
          } else if (this.scope.type === this.user) {
            params.follow_userid = this.scope.ids[0]
          }
        }

        let body = JSON.parse(JSON.stringify(this.params))
        body = body.map((item) => {
          item.operator = this.operator_exp
          item.attrvalues.forEach((vitem, index) => {
            vitem.order = index
            vitem.operator = vitem.operator ? 1 : 0
            if (vitem.fuzzy === 0 && vitem.keyvalues.length > 0) {
              vitem.keyvalue = vitem.keyvalues.join(',')
            }
            vitem.fuzzy = vitem.fuzzy === 1 ? true : false
            conditionkey.set(vitem.keyid, vitem.keyid)
            delete vitem.keyvalues
          })
          return item
        })
        // 按照业务属性查询客户人数
        queryCustListByExp(params, body).then((res) => {
          if (res.code === 0) {
            let list = []
            list = res.data.map((item) => {
              if (item.attrs && item.attrs.length > 0) {
                let attrs = new Array()
                item.attrs.forEach((vi, index) => {
                  if (conditionkey.has(vi.keyid)) {
                    attrs.push(vi)
                  }
                })
                item.attrs = attrs
              }
              return item
            })
            this.custlist = list
          }
        })
      }
    },
    paramConvert(params) {
      // 查询参数转换
      // 参数转换
      let param = JSON.parse(JSON.stringify(params))
      return param.map((item) => {
        item.operator = this.operator_exp
        item.attrvalues.forEach((vitem, index) => {
          vitem.order = index
          vitem.operator = vitem.operator ? 1 : 0
          if (vitem.fuzzy === 0 && vitem.keyvalues.length > 0) {
            vitem.keyvalue = vitem.keyvalues.join(',')
          }
          vitem.fuzzy = vitem.fuzzy === 1 ? true : false
          delete vitem.keyvalues
        })
        return item
      })
    },
    paramReVert(params) {
      // 参数还原
      let param = JSON.parse(JSON.stringify(params))
      return param.map((item) => {
        item.attrvalues.forEach((vitem, index) => {
          vitem.order = index
          vitem.operator = vitem.operator == 1 ? true : false
          if (!vitem.fuzzy) {
            vitem.keyvalues = vitem.keyvalue.split(',')
          }
          vitem.fuzzy = vitem.fuzzy ? 1 : 0
        })
        return item
      })
    },
    chooseGroup() {
      // 选择群函数
      // 选择群
      this.groupVisiable = true
      // followuserList({
      //   userid: this.userid,
      //   type: 1,
      // }).then((res) => {
      //   this.treeDepart = this.renderTreeNodes(res.data)
      //   generateList(this.treeDepart)
      // })
    },
    searchDepart(e) {
      // 搜索部门
      const value = e.target.value
      const expandedKeys = dataList
        .map((item) => {
          if (item.title.indexOf(value) > -1) {
            return getParentKey(item.key, this.treeDepart)
          }
          return null
        })
        .filter((item, i, self) => item && self.indexOf(item) === i)
      Object.assign(this, {
        expandedKeys,
        searchValue: value,
        autoExpandParent: true,
      })
    },
    onExpand(expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onSelect(selectedKeys, info) {
      this.selectedKeys = selectedKeys
    },
    onCheck(checkedKeys, evt) {
      // 部门选中事件函数
      this.checkedKeys = checkedKeys
      // 获取当前选中部门id
      let key = evt.node.eventKey
      if (key) {
        key = key.substring(7)
      }
      if (!evt.node.checked) {
        // 部门选中
        // 保存当前的群列表
        let currentGroups = new Map()
        this.checkedGroups.forEach((item) => {
          currentGroups.set(item.id, item.name)
        })
        // 查询当前部门群数据
        listBydeptid({ deptid: key }).then((res) => {
          if (res.code == 0) {
            res.data.forEach((item) => {
              if (!currentGroups.has(item.chat_id)) {
                this.checkedGroups.push({
                  id: item.chat_id,
                  name: item.name,
                  owner: item.owner.name,
                  ownerid: item.owner.userid,
                  depart: key,
                })
              }
            })
            // 将部门和群列表保存
            this.checkedDepart.set(key, res.data)
          }
        })
      } else {
        // 部门取消选中
        // 查询当前部门群数据
        listBydeptid({ deptid: key }).then((res) => {
          if (res.code == 0) {
            // 保存当前部门群列表
            let departGroups = new Map()
            res.data.forEach((item) => {
              departGroups.set(item.chat_id, item.name)
            })
            let groups = new Array()
            this.checkedGroups.forEach((item) => {
              if (!departGroups.has(item.id)) {
                groups.push({
                  id: item.id,
                  name: item.name,
                  owner: item.owner.name,
                  ownerid: item.owner.userid,
                  depart: key,
                })
              }
            })
            this.checkedGroups = groups

            // 删除已选部门及群信息
            this.checkedDepart.delete(key)
          }
        })
      }
    },
    delGroup(item) {
      // 删除已选择的群
      let departid = `${item.depart}`
      let groups = this.checkedDepart.get(departid)

      if (groups.length === 1) {
        // 删除已选部门
        this.checkedDepart.delete(departid)
        this.checkedKeys.checked = this.checkedKeys.checked.filter((key) => {
          return key !== `dept_id${departid}`
        })
      } else {
        groups = groups.filter((ele) => {
          return ele.chat_id !== item.id
        })
        this.checkedDepart.set(departid, groups)
      }
      this.checkedGroups = this.checkedGroups.filter((ele) => {
        return ele.id !== item.id
      })
    },
    renderTreeNodes(data) {
      // 渲染树形节点
      const setData = data.map((item) => {
        // 判断当前登录人权限范围 0表示本人,1 表示全部,2表示部分
        if (item.children && item.children.length === 0 && !item.id.startsWith('dept_id')) {
          item = {}
        } else {
          this.renderTreeNodes(item.children)
        }
        return item
      })
      return setData
    },
    confirmGroups() {

      if (this.selectedGroupIds.length === 0) {
        this.$message.error('请选择群')
        return
      }

      let param = {}
      let params = new Array()
      param.type = this.value
      param.params = this.checkedGroups
      this.groupVisiable = false
      this.group_count = this.selectedGroupIds.length
      param.scope = this.scope
      this.$emit('callback', param)
    },
    queryGroupList(body) {
      queryCustomerGroupList(body).then((res) => {
        if (res.code === 0) {
          this.groups = res.data.records
        }
      })
    },
    onGroupSelectChange(selectedKeys) {
      // 群选中事件
      this.selectedGroupIds = selectedKeys
      this.selectedGroupIds.forEach((id) => {
        this.groups.forEach(item =>{
          if (item.chat_id === id) {
            this.checkedGroups.push({ id: item.chat_id, name: item.name, owner: item.owner.name, ownerid: item.owner.userid })
          }
        })
        this.checkedGroups = this.checkedGroups.filter(item => this.selectedGroupIds.includes(item.id))
      })
    },
    searchGroup() { // 搜索群聊
      this.selectedGroupIds = []
      if (this.input !== '') {
        this.groups = this.groups.filter((item) => item.name.indexOf(this.input) >= 0)
      } else {
        if (this.scope.type === 'org') {
          this.queryGroupList({ pageno: this.upagination.current - 1, owner_deptid: this.scope.ids[0] })
        } else if (this.scope.type === 'user') {
          this.queryGroupList({ pageno: this.upagination.current - 1, owner_userid: this.scope.ids[0] })
        }
      }
    },
    tableChange(pagination, filters, sorter, { currentDataSource }) { // 群聊表格翻页事件函数
      if (this.scope.type === 'org') {
        this.queryGroupList({ pageno: pagination.current - 1, pagesize: pagination.pageSize,  owner_deptid: this.scope.ids[0] })
      } else if (this.scope.type === 'user') {
        this.queryGroupList({ pageno: pagination.current - 1, pagesize: pagination.pageSize, owner_userid: this.scope.ids[0] })
      }
    }
  },
  components: {
    'p-csm': csm
  }
}
</script>
<style scoped>
.panel {
  width: 100%;
  min-height: 50px;
  background-color: #fbfbfb;
  border-radius: 5px;
  padding: 10px 10px;
  border: 1px solid #eee;
}

.body {
  margin-top: 10px;
}

.viewmembers {
  background-color: #ecf8fe;
  margin-top: 20px;
  padding: 0px 5px;
  width: auto;
  display: inline-block !important;
  display: inline;
}

.ant-modal-content {
  position: relative;
  background-color: #fff;
  background-clip: padding-box;
  border: 0;
  border-radius: 4px;
  -webkit-box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  pointer-events: auto;
}

.dialog .dialog-content {
  height: 100%;
}

.ant-modal-title {
  font-size: 17px;
  width: 100%;
  text-align: center;
  margin-top: 2px;
  font-weight: 600;
  line-height: 24px;
  letter-spacing: 1px;
}

.all-member-list {
  padding-right: 20px;
  height: 360px;
  overflow-y: auto;
  margin-bottom: 0;
}

.all-member-right-list {
  margin-left: -17px;
  padding-right: 20px;
  height: 400px;
  overflow-y: auto;
  margin-bottom: 0;
}

.add-member-right {
  padding-top: 28px;
  padding-left: 31px;
  float: left;
  text-align: center;
}

.add-member-right .selected-members-list {
  height: 348px;
  overflow-y: auto;
}

/* .ant-select {
  min-width: 120px;
} */
</style>
<style>
.ant-modal-body {
  padding: 10px;
  font-size: 14px;
  line-height: 1.5;
  word-wrap: break-word;
}
</style>